package com.xm.task;

import com.xm.entity.UserP;
import com.xm.util.DataSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * jdbc(sql内置拼接) 批量插入数据任务
 */
@Slf4j
public class JdbcInsertTask implements Runnable {
    private final List<UserP> users;
    public JdbcInsertTask(List<UserP> users) {
        this.users = users;
    }

    @Override
    public void run() {
        if(!CollectionUtils.isEmpty(users)) {
            long start = System.currentTimeMillis();
            //1、注册驱动
            //2、创建数据库连接
//            long start2 = System.currentTimeMillis();
//            conn = DataSourceUtil.getHikariConnection();
//            conn = DataSourceUtil.getC3p0Connection();
//            log.info("从数据库连接池获取连接，耗时{}ms", System.currentTimeMillis() - start2);
            try (Connection conn = DataSourceUtil.getHikariConnection();) {
                //3、开启事务/取消事务自动提交
                conn.setAutoCommit(false);
                //4、执行SQL 获取结果集
                String sql = "INSERT INTO `user` " +
                        "(`uuid`, `name`, `height`, `weight`, `age`, `bool`, `signature`, `delMark`, `createTime`, `updateTime`, `long_field`) " +
                        "VALUES " +
                        "(?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)";
                try (PreparedStatement ps = conn.prepareStatement(sql)) {
                    for (UserP user : users) {
                        ps.setString(1, user.getUuid());
                        ps.setString(2, user.getName());
                        ps.setBigDecimal(3, user.getHeight());
                        ps.setBigDecimal(4, user.getWeight());
                        ps.setInt(5, user.getAge());
                        ps.setBoolean(6, user.getBool());
                        ps.setString(7, user.getSignature());
                        ps.setString(8, user.getCreateTimeStr());
                        ps.setString(9, user.getUpdateTimeStr());
                        ps.setString(10, user.getLongField());
                        ps.addBatch();
                    }
                    ps.executeBatch();
                    conn.commit();
                    ps.clearBatch();
                }
            } catch (SQLException e) {
                //5、关闭连接（try-with-resources 异常或结束后会自动关闭资源）
                log.error("JdbcInsertTask 批量插入数据异常！e={}", e.getMessage());
                throw new RuntimeException(e);
            } finally {
                int total = users.size();
                long time = System.currentTimeMillis() - start;
                long totalTime = DataSourceUtil.atomicLong.addAndGet(time);
                log.info("JdbcInsertTask 批量插入{}条数据，耗时{}ms，totalTime={}", total, time, totalTime);
            }
        }
    }

}
